<template>
  <div
    class="page-mark-middle"
    @click.prevent="panelClick"
    @mousemove="panelMouseMove($event)"
    ref="middleMark"
  >
    <grid-layout
      :layout.sync="layout"
      :col-num="24"
      :row-height="30"
      :is-draggable="true"
      :is-resizable="true"
      :is-mirrored="false"
      :vertical-compact="false"
      :margin="[grid.horizontal, grid.vertical]"
      :use-css-transforms="true"
      @layout-updated="layoutUpdatedEvent"
    >
      <grid-item
        v-for="(item,index) in layout"
        :x="item.x"
        :y="item.y"
        :w="item.w"
        :h="item.h"
        :i="item.i"
        :key="item.i"
        :ref="components[index].id"
        :style="components[index].style"
        @click.native.stop="selectItem(index)"
        @contextmenu.native.stop="contextmenuEvt($event,index)"
        @resized="resizedEvent"
        @move="moveEvent"
        @moved="movedEvent"
        :class="{'active': activeIndex === index}"
      >
        <component
          :is="components[index].name"
          :data="components[index]"
          :index="index"
          @updateResult="updateResult"
        ></component>
      </grid-item>
    </grid-layout>

    <!-- 右击菜单 -->
    <context-menu v-if="menuShow" :left="menuLeft" :top="menuTop" @remove="remove" />
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import { deepCopy } from 'assets/scripts/common';
import VueGridLayout from 'vue-grid-layout';
import ContextMenu from './ContextMenu';
import { navCollapsedWidth, navExpandWidth, defaultTopHeight, leftWidth } from './config/code';
// 基础组件
import textItem from './Middle/Basic/TextItem';
import inputItem from './Middle/Basic/InputItem';
import selectItem from './Middle/Basic/SelectItem';
import switchItem from './Middle/Basic/SwitchItem';
import datepickerItem from './Middle/Basic/DatepickerItem';
import buttonItem from './Middle/Basic/ButtonItem';
import checkboxItem from './Middle/Basic/CheckboxItem';
import radioItem from './Middle/Basic/RadioItem';
import checkboxgroupItem from './Middle/Basic/CheckboxgroupItem';
import radiogroupItem from './Middle/Basic/RadiogroupItem';
import rateItem from './Middle/Basic/RateItem';
import tableItem from './Middle/Basic/TableItem';
// 高级组件
import sectionItem from './Middle/Senior/SectionItem';
import delimitItem from './Middle/Senior/DelimitItem';

import bus from 'assets/scripts/bus';
import { getTemplateDetail } from 'http/api/mark'
export default {
  components: {
    textItem,
    inputItem,
    switchItem,
    selectItem,
    datepickerItem,
    buttonItem,
    checkboxItem,
    radioItem,
    checkboxgroupItem,
    radiogroupItem,
    rateItem,
    tableItem,
    sectionItem,
    delimitItem,
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    ContextMenu
  },
  computed: {
    ...mapState({
      layout: state => state.mark.layout,
      components: state => state.mark.components,
      activeCom: state => state.mark.activeCom,
      grid: state => state.mark.grid,
      menuShow: state => state.mark.menuShow,
      navCollapsed: state => state.app.navCollapsed
    })
  },
  data () {
    return {
      activeIndex: null,
      menuLeft: 10,
      menuTop: 10,
      editId: null
    };
  },
  methods: {
    ...mapMutations([
      'setActiveCom',
      'resetComponents',
      'resetLayout',
      'setComponents',
      'setMenuShow'
    ]),
    ...mapActions(['removeActiveCom', 'changeActiveCom']),

    // 移动组件的取消选中
    moveEvent () {
      document.body.style.userSelect = 'none';
    },

    movedEvent () {
      document.body.style.userSelect = '';
    },

    layoutUpdatedEvent (newLayout) {
      console.log('Updated layout: ', newLayout);
    },

    resizedEvent (i, newH, newW, newHPx, newWPx) {
      console.log('大小正在改变', i, newH, newW, newHPx, newWPx);
      this.layout[i].height = newHPx
      this.layout[i].width = newWPx
    },

    // 右击显示
    contextmenuEvt (e, index) {
      e.preventDefault();

      // 设置当前是激活组件
      this.selectItem(index);

      // 获取点击的位置并显示
      let posX = this.navCollapsed ? navCollapsedWidth : navExpandWidth;
      let posY = defaultTopHeight;
      let scrollTop = this.$refs.middleMark.scrollTop;

      this.menuLeft = e.pageX - posX - leftWidth;
      this.menuTop = e.pageY + scrollTop - posY;
      this.setMenuShow(true);
    },

    // 更新结果
    updateResult (data) {
      let item = this.components[data.index];
      item.value = data.value;

      // 更新结果
      this.changeActiveCom(item)
    },

    // 阻止默认拖拽会选中文本的操作
    panelMouseMove (e) {
      e.preventDefault();
    },

    // 面板的点击 -- 用于取消激活组件的选中
    panelClick (e) {
      if (e.target.classList.contains('page-mark-middle')) {
        this.activeIndex = null;
        this.setActiveCom(null);
        this.setMenuShow(false);
      }
    },

    // 外界通信激活index
    setMiddleActiveStyle (index) {
      this.activeIndex = index;
    },

    // 点击item
    selectItem (index) {
      this.activeIndex = index;
      let item = this.components[index];
      item.location = this.layout[index];
      this.setActiveCom(deepCopy(item));
    },

    // 获取中间内容的滚动
    getMiddleContentScroll () {
      sessionStorage.middleScrollTop = this.$refs.middleMark.scrollTop
    },

    // 获取模板数据
    getTemplateData () {
      if (this.editId) {
        getTemplateDetail({ id: this.editId }).then(res => {
          if (res.data) {
            let { config, desc, id, name } = res.data;
            let { layout, components } = config;
            this.resetLayout(layout);
            this.resetComponents(components)
            bus.$emit('setHeaderData', { desc, id, name })
          }
        })
      }
    },

    // 移除组件
    remove () {
      this.activeIndex = null
      this.removeActiveCom(deepCopy(this.activeCom));
      this.setMenuShow(false);
    },

    /**
     * 鼠标按键事件
     */
    keyUpEvt (e) {
      e.preventDefault();
      const keyCode = e.keyCode || e.which;

      var type = e.srcElement ? e.srcElement.type : e.target.type;
      if (type === 'text' || type === 'textarea') {
        return;
      }

      if (keyCode === 46 && this.activeCom) {
        this.remove()
      }
    }
  },
  mounted () {
    // 鼠标按键事件
    document.addEventListener('keyup', this.keyUpEvt);
    bus.$on('setMiddleActiveStyle', this.setMiddleActiveStyle);
    bus.$on('getMiddleContentScroll', this.getMiddleContentScroll);

    this.editId = this.$route.query.id || '';
    this.getTemplateData();
  },
  beforeDestroy () {
    document.removeEventListener('keyup', this.keyUpEvt);
    bus.$off('setMiddleActiveStyle', this.setMiddleActiveStyle);
    bus.$off('getMiddleContentScroll', this.getMiddleContentScroll);
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
@import '../../assets/theme/themeBlue.less';
.page-mark-middle {
  position: absolute;
  left: 200px;
  right: 260px;
  bottom: 0;
  top: 50px;
  // margin: 0 10px;
  // padding: 10px;
  background: url('~assets/images/canvas-bg.png');
  overflow-y: auto;

  .active {
    outline: #00b195 1px solid;
    outline-offset: 2px;
  }

  .vue-grid-item {
    background: #ffffff;
  }
}
</style>
